package com.server.core;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public abstract class Scanner {

    private Timer                       timer;
    private TimerTask                   task;
    private File                        rootDir;
    private int                         interval;
    private boolean                     running = false;
    private final Map<String, TimeSize> preScan = new HashMap();
    private final Map<String, TimeSize> curScan = new HashMap();

    public Scanner(String rootDir, int interval) {
        if ((rootDir == null) || (rootDir.equals("")))
            throw new IllegalArgumentException("The parameter rootDir can not be blank.");
        this.rootDir = new File(rootDir);
        if (!this.rootDir.isDirectory())
            throw new IllegalArgumentException("The directory " + rootDir + " is not exists.");
        if (interval <= 0)
            throw new IllegalArgumentException("The parameter interval must more than zero.");
        this.interval = interval;
    }

    public abstract void onChange();

    private void working() {
        scan(this.rootDir);
        compare();
        this.preScan.clear();
        this.preScan.putAll(this.curScan);
        this.curScan.clear();
    }

    private void scan(File file) {
        if ((file == null) || (!file.exists())) {
            return;
        }
        if (file.isFile()) {
            try {
                this.curScan.put(file.getCanonicalPath(), new TimeSize(file.lastModified(), file.length()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (file.isDirectory()) {
            File[] fs = file.listFiles();
            if (fs != null) {
                File[] arrayOfFile1;
                int j = (arrayOfFile1 = fs).length;
                for (int i = 0; i < j; i++) {
                    File f = arrayOfFile1[i];
                    scan(f);
                }
            }
        }
    }

    private void compare() {
        if (this.preScan.size() == 0) {
            return;
        }
        if (!this.preScan.equals(this.curScan))
            onChange();
    }

    public void start() {
        if (!this.running) {
            this.timer = new Timer("JFinal-Scanner", true);
            this.task = new TimerTask() {

                public void run() {
                    Scanner.this.working();
                }
            };
            this.timer.schedule(this.task, 1010L * this.interval, 1010L * this.interval);
            this.running = true;
        }
    }

    public void stop() {
        if (this.running) {
            this.timer.cancel();
            this.task.cancel();
            this.running = false;
        }
    }
}
